import Taro, { useLoad } from "@tarojs/taro";
import {
  View,
  Form,
  Button,
  Image,
  Input,
  Label,
  Text,
} from "@tarojs/components";
import { H5Login, H5_cfgs, wxjs_cfgs } from "@/api";
import { useRequest, useSetState } from "ahooks";

import logoIcon from "@/static/logo.jpg";
import "./index.module.scss";
// import { json } from 'stream/consumers'

import wx from "weixin-js-sdk";

export default function LoginPage() {
  const [form, setForm] = useSetState({
    sn: "",
    pwd: "",
    invite_code: "",
    openid: Taro.getStorageSync("openid") || "",
    // openid:'olg4N62BxeVrUkv_EjYHVJqnPotc'
  });

  useLoad(() => {
  var userAgent = navigator.userAgent.toLowerCase();

  if (userAgent.indexOf('micromessenger') !== -1) {
      console.log('This is WeChat Browser');
      console.log('Taro.getCurrentPages()',Taro.getCurrentPages())
    // Taro.hideHomeButton()
    if (Taro.getStorageSync("userInfo")?.token) {
      Taro.reLaunch({
        url: "/pages/index/index",
      });
    }
    if (!Taro.getStorageSync("openid")) {
      H5_cfgs({
        url: window.location.origin,
      }).then((res) => {
        parseParams().then((d) => {
          if (d.openid == null || d.openid === "") {
            window.location.href = res?.data?.url;
          } else {
            setForm({ openid: d?.openid });
            Taro.setStorageSync("openid", d.openid);
          }
        });
      });

      wxjs_cfgs({
        url: window.location.origin,
      }).then((res) => {
        // 配置微信JS-SDK
        wx.config(res?.data);
        wx.error((err) => {
          // 微信JS-SDK配置成功后，获取微信用户信息
          console.log('ready',err)
        });
      });
    }
  } else {
      console.log('This is not WeChat Browser');
  }
  });

  const { loading, run } = useRequest(H5Login, {
    manual: true,
    onSuccess: (res) => {
      Taro.setStorageSync("userInfo", res?.data);
      Taro.reLaunch({
        url: "/pages/index/index",
      });
    },
  });

  const scanCode = () => {

    wx.checkJsApi({
      jsApiList: ["scanQRCode"],
      success: (res) => {
        console.log("ressss", res);
        wx.scanQRCode({
          needResult: 1,
          success: (scan) => {
            setForm({ sn: scan‌.resultStr}); // 获取扫描结果
          },
          fail: (err) => {
            alert(JSON.stringify(err));
          },
        });
      },
      fail: (err) => {
        alert('不支持 扫码'+JSON.stringify(err));
      },
    });

    // Taro.scanCode({
    //   success: ({ result: sn }) => {
    //     setForm({ sn });
    //     console.log("success", sn);
    //     alert(JSON.stringify(sn))
    //   },
    //   fail: ({ errMsg }) => {
    //     alert(JSON.stringify(errMsg))
    //     Taro.showToast({
    //       title: errMsg,
    //       icon: "none",
    //     });
    //   },
    // });
  };
  // 解析路径
  const parseParams = async () => {
    let url = window.location.href.split("#")[0];
    const str = url.substr(url.indexOf("?") + 1);
    const arr = str.split("&");
    const result = {};
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i].split("=");
      result[item[0]] = item[1];
    }
    return result;
  };
  // 登陆
  const loginbtn = async () => {
    if (!form?.sn)
      return Taro.showToast({ title: "请扫码或输入设备号", icon: "none" });
    if (!form?.pwd)
      return Taro.showToast({ title: "请输入密码", icon: "none" });
    // Taro.login({
    //   success: ({ code }) => {
    //     run({
    //       code,
    //       ...form
    //     })
    //   },
    //   fail: (res) => {
    //     console.log(res)
    //   }
    // })
    run(form);
    return;

    Taro.setStorageSync("userInfo", {
      active_time: "",
      agent_id: "10554",
      balance: 464,
      bind_time: "",
      bonus_rmb: 0,
      bonus_share: 0,
      bonus_vip: 0,
      bonus_vip_1: 0,
      bonus_vip_2: 0,
      can_bonus_share: false,
      can_invite: false,
      child_cnt: 2,
      company_id: 154456,
      create_time: "2023-06-02 22:54:05",
      curr_pay_time: "2024-08-26 22:10:37",
      customer_no: "8435844701100OI",
      earn: 845,
      id: 1,
      invite_code: "000001",
      invite_rmb: "14317.0",
      invite_score: "5.72",
      invite_sn: null,
      invite_time: "",
      is_vip: null,
      last_login_ip: "125.69.144.180",
      last_login_time: "2023-06-26 20:01:46",
      left_months: "-",
      left_months2: "-",
      login_count: 28,
      min_trans_money: "10000.0",
      name: null,
      open_vip: false,
      openid: "ooKR25CEj0vk5NjK4SfQ174dyc7w",
      rmb_balance: "0.00",
      sim_fee: "0.00",
      sim_fee_time: "",
      sn: "00002402106040201384",
      sub_gzh: "已关注",
      sub_time: "2023-06-26 20:18:14",
      token: "458d6e5b8d7e45f5b32e38f0bd30db9e",
      tusn: "201384",
      tusn_prefix: "0000240210604",
      unit: "积分",
      unsub_time: "",
      vip_expire_time: "",
      vip_memo: "iii",
    });
    Taro.reLaunch({
      url: "/pages/index/index",
    });
  };
  return (
    <View className="login-box">
      <Image className="logo" src={logoIcon} />
      <View className="text-lg padding-tb">登录花码数据</View>
      <Form onSubmit={loginbtn}>
        <View className="padding-bottom margin-bottom">
          <Label for="sn" className="cu-form-group">
            <View style={{ display: "flex" }}>
              <Input
                value={form.sn}
                onInput={(e) => setForm({ sn: e?.target?.value || "" })}
                placeholder="请扫码或输入设备号"
              />
              <Text
                onClick={scanCode}
                className="iconfont icon-saoma text-ls text-cc padding-lr-sm"
              ></Text>
            </View>
          </Label>
          <Label for="pwd" className="cu-form-group border-bottom">
            <Input
              password
              onInput={(e) => setForm({ pwd: e?.target?.value || "" })}
              placeholder="请输入密码"
            />
          </Label>
          <Label for="invite_code" className="cu-form-group border-bottom">
            <Input
              onInput={(e) => setForm({ invite_code: e?.target?.value || "" })}
              placeholder="请输入邀请码"
            />
          </Label>
        </View>
        <Button
          loading={loading}
          disabled={loading}
          className="text-lg text-center margin-bottom main-bc padding-tb-xs round line-white"
          formType="submit"
        >
          登录
        </Button>
      </Form>
    </View>
  );
}
